package com.util;

import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;

import org.apache.log4j.Logger;

import com.lobby.httpclient.SignUtils;

/**
 * 图片存放类
 * @author wwl
 *
 */
public class Test {
	
	static Logger logger=Logger.getLogger(Test.class);
	private  String srcpath="";														//源图片路径名称
	private  String subpath = "/home/apache-tomcat-7.0.47/webapps/image/face/";		//剪切图片存放路径名称
	//private  String srcpath="G:/image/detection/123456.jpg";
	//private  String subpath = "G:/image/copy/wwl";
    private static final String IMAGE_FORM_OF_JPG = "jpg";	//jpg图片格式
    private static final String IMAGE_FORM_OF_PNG = "png";	//png图片格式
    private int x;			//剪切点x坐标
    private int y;			//剪切点y坐标
    private int width;		//剪切点宽度
    private int height;		//剪切点高度

    public Test() {
    }
    
    public Test(int x, int y, int width, int height) {
        this.x = x;
        this.y = y;
        this.width = width;
        this.height = height;
    }

    public static void main(String[] args) throws Exception {
        //Test Test = new Test(139-70, 93-46,104+250, 104+250);
    	//Test Test = new Test(847-150, 833/2+100,897+250, 897+250);
    	//Test Test = new Test(892-150, 788/2+100,907+250, 907+250);
    	//Test Test = new Test(316/2,584/2,427+250, 427+250);
    	//Test Test = new Test(60-60/4,70-70/3,91+91/2,91+91/2);
    	//Test Test = new Test(501-501/4,48-48/3,94+94/2,94+92/2);
        //Test.cut(Test.getSrcpath(), Test.getSubpath());
    	/*String s=DataUtil.getRandomString(16);
    	Date data=new Date();
        SimpleDateFormat dateFormat=new SimpleDateFormat("yyyyMMddHHmmss");
        String newData = dateFormat.format(data); 
        System.out.println(newData+s);*/
    	/*String fileSuffixImg=".jpg";
    	String index=".jpg";
    	if(!fileSuffixImg.equals(index)){
    		System.out.println("ji");
    	}*/
    	//String url = "https://openapi-test.colourlife.com/v1/gfjg/pay/unifiedorder";
        /*Map<String, String> testParam = new HashMap<String, String>();
        testParam.put("app_uuid","ICEEANQUAN-ADC5-42B8-BB2E-BC39B211FDED");
        testParam.put("timestamp", "1514260873");
        String md5=SignUtils.getSignature(testParam);
        logger.info("统一下单接口,生成md5:"+md5);*/
    	String str="appID=ICEEANQUAN-ADC5-42B8-BB2E-BC39B211FDED&business_uuid=e3ccf625-ee0e-44a4-b138-fa02859dea04&device_info=CZYAPP&nonce_str=B49FDC9714EFBE144FFD148A9514FF4B09759D8F&open_id=e80fe9a4390523ff25cd9ee57ce7cd49&trade_type=JSAPI&total_fee=1&discount=100&payment_uuid=1025f6c4eedfcd92462b8b7383257877&payment_name=%E5%BD%A9%E4%B9%8B%E4%BA%91%E5%BE%AE%E4%BF%A1%E6%94%AF%E4%BB%98&colour_sn=201801_2d06ca3158bc2549935aba15de0110d40ff8&out_trade_no=20180103100600"
    			+ "&attach=10yid607phone13424367370&time_pay=1514945183&colour_trade_no=1681000201801031001316372381&trade_state=2&signature=9B84BCC3B1A5EB6D65F39CFD1C7DAC5A";
    	String sub_attach1=str.substring(str.indexOf("yid")+3, str.indexOf("phone"));
    	String sub_attach2=str.substring(str.indexOf("phone")+5, str.indexOf("&time_pay"));
    	System.out.println(sub_attach1);
    	System.out.println(sub_attach2);
    	/*String sub_attach2=str.substring(str.indexOf("mobile"), str.indexOf("&detail"));
    	String index=sub_attach1.substring(4);
    	String index2=sub_attach2.substring(7);
    	System.out.println(index);
    	System.out.println(index2);*/
    }
    /**
     * 返回包含所有当前已注册 ImageReader 的 Iterator，这些 ImageReader 声称能够解码指定格式。
     * 参数：formatName - 包含非正式格式名称 .（例如 "jpeg" 或 "tiff"）等 。
     * 
     * @param postFix
     *            文件的后缀名
     * @return
     */
    public Iterator<ImageReader> getImageReadersByFormatName(String postFix){
        switch (postFix) {
        case IMAGE_FORM_OF_JPG:
            return ImageIO.getImageReadersByFormatName(IMAGE_FORM_OF_JPG);
        case IMAGE_FORM_OF_PNG:
            return ImageIO.getImageReadersByFormatName(IMAGE_FORM_OF_PNG);
        default:
            return ImageIO.getImageReadersByFormatName(IMAGE_FORM_OF_JPG);
        }
    }
    
    
    /**
     * 根据字节，判断文件类型
     * @param path
     * @return
     * @throws IOException
     */
    public static String getFileSuffix(String path) throws IOException {  
        String result = "";  
        String hex="";  
        if (path != null) {  
            File image=new File(path);  
            InputStream is = new FileInputStream(image);  
            byte[] bt = new byte[2];    
            is.read(bt);   
            logger.info(bt+"\n"+bytesToHexString(bt));    
            hex=bytesToHexString(bt);  
            is.close();  
            if(hex.equals("ffd8")){  
                result=".jpg";  
            }else if(hex.equals("4749")){  
                result=".gif";  
            }else if(hex.equals("8950")){  
                result=".png";  
            }  
        }
        return result;  
    }  
    /**
     * 对图片裁剪，并把裁剪完蛋新图片保存 。
     * @param srcpath 源图片路径
     * @param subpath 剪切图片存放路径
     * @throws IOException
     */
    public String cut(String srcpath, String subpath) throws IOException {
        FileInputStream is = null;
        ImageInputStream iis = null;
        try {
        	// 读取图片文件
            is = new FileInputStream(srcpath);
            // 获取文件的后缀名
            String postFix = getPostfix(srcpath);
            System.out.println("图片格式为：" + postFix);
            logger.info("图片格式为:"+ postFix);
            /*
             * 返回包含所有当前已注册 ImageReader 的 Iterator，这些 ImageReader 声称能够解码指定格式。
             * 参数：formatName - 包含非正式格式名称 .（例如 "jpeg" 或 "tiff"）等 。
             */
            Iterator<ImageReader> it = getImageReadersByFormatName(postFix);
            ImageReader reader = it.next();
            // 获取图片流
            iis = ImageIO.createImageInputStream(is);
            /*
             * <p>iis:读取源.true:只向前搜索 </p>.将它标记为 ‘只向前搜索’。
             * 此设置意味着包含在输入源中的图像将只按顺序读取，可能允许 reader 避免缓存包含与以前已经读取的图像关联的数据的那些输入部分。
             */
            reader.setInput(iis, true);
            /*
             * <p>描述如何对流进行解码的类<p>.用于指定如何在输入时从 Java Image I/O
             * 框架的上下文中的流转换一幅图像或一组图像。用于特定图像格式的插件 将从其 ImageReader 实现的
             * getDefaultReadParam 方法中返回 ImageReadParam 的实例。
             */
            ImageReadParam param = reader.getDefaultReadParam();
            /*
             * 图片裁剪区域。Rectangle 指定了坐标空间中的一个区域，通过 Rectangle 对象
             * 的左上顶点的坐标（x，y）、宽度和高度可以定义这个区域。
             */
            Rectangle rect = new Rectangle(x, y, width, height);
            // 提供一个 BufferedImage，将其用作解码像素数据的目标。
            param.setSourceRegion(rect);
            /*
             * 使用所提供的 ImageReadParam 读取通过索引 imageIndex 指定的对象，并将 它作为一个完整的
             * BufferedImage 返回。
             */
            BufferedImage bi = reader.read(0, param);
            // 保存新图片
            Date data=new Date();
            SimpleDateFormat dateFormat=new SimpleDateFormat("yyyyMMddHHmmss");
            String newData = dateFormat.format(data); 
            String s=DataUtil.getRandomString(16);
            ImageIO.write(bi, postFix, new File(subpath + "_" + newData + s + "." + postFix));
            String path="http://wwl.ycws.cc/image/face/" + "_" + newData + s +"." + postFix;		//按比例截取后的人脸图片
            return path;
        } finally {
            if (is != null)
                is.close();
            if (iis != null)
                iis.close();
        }
       
    }
    
    public static String bytesToHexString(byte[] src) {    
        StringBuilder stringBuilder = new StringBuilder();    
        if (src == null || src.length <= 0) {    
            return null;    
        }    
        for (int i = 0; i < src.length; i++) {  
            int v = src[i] & 0xFF;    
            String hv = Integer.toHexString(v);    
            if (hv.length() < 2) {    
                stringBuilder.append(0);    
            }    
            stringBuilder.append(hv);    
        }    
        return stringBuilder.toString();    
    }  
    /**
     * 获取inputFilePath的后缀名，如："e:/test.pptx"的后缀名为："pptx"<br>
     * @param inputFilePath
     * @return
     */
    public String getPostfix(String inputFilePath) {
        return inputFilePath.substring(inputFilePath.lastIndexOf(".") + 1);
    }

    public int getHeight() {
        return height;
    }

    public void setHeight(int height) {
        this.height = height;
    }

    public String getSrcpath() {
        return srcpath;
    }

    public void setSrcpath(String srcpath) {
        this.srcpath = srcpath;
    }

    public String getSubpath() {
        return subpath;
    }

    public void setSubpath(String subpath) {
        this.subpath = subpath;
    }
    
    public int getWidth() {
        return width;
    }

    public void setWidth(int width) {
        this.width = width;
    }

    public int getX() {
        return x;
    }

    public void setX(int x) {
        this.x = x;
    }

    public int getY() {
        return y;
    }

    public void setY(int y) {
        this.y = y;
    }
}